package edu.hunau.aop.factory;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.lang.reflect.Proxy;

/**
 * @author hb
 * @date 2022-11-29 11:49:35
 */
public class ProxyFactory {
    private static ProxyFactoryBean proxyFactory;
    public static Object getBean(String targename) throws Exception {
        Object target = crateObj(targename);
        Object obj = Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), proxyFactory);
        return obj;
    }
    /* 根据输入的字符串，为代理类注入target属性赋值 */
    public static Object crateObj(String targetname) throws Exception {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new File("./src/main/resources/beans.xml"));
        Element root = doc.getRootElement();
        /* 获得代理工厂的全限定名 */
        Element proxyEle = (Element) root.selectNodes(
                "bean[@id='" + targetname + "']").get(0);
        String proxyClass = proxyEle.attributeValue("class");
        // 获得property标签中的name属性值 和 loc属性值
        Element proEle = (Element) proxyEle.selectNodes("property").get(0);
        String nameValue = proEle.attributeValue("name");
        String locValue = proEle.attributeValue("loc");
        /* 根据locValue获得目标对象的权限定名 */
        Element targetEle = (Element) root.selectNodes(
                "bean[@id='" + locValue + "']").get(0);
        String targetClass = targetEle.attributeValue("class");
        /*获得目标对象的id和对象*/
        Element intEle = (Element) proxyEle.selectNodes("property").get(1);
        String intValue = intEle.attributeValue("name");
        String intlocValue = intEle.attributeValue("loc");
        Element interEle = (Element) root.selectNodes(
                "bean[@id='" + intlocValue + "']").get(0);
        String interClass = interEle.attributeValue("class");
        //	System.out.println(intlocValue+ "  interClass=="+interClass);
        Object interObj = Class.forName(interClass).newInstance();
        /* 通过反射创建 target对象 */
        Object target = Class.forName(targetClass).newInstance();
        /* 根据代理工厂的权限定名为属性赋值 */
        proxyFactory =
                (ProxyFactoryBean) Class.forName(proxyClass).newInstance();
        Class.forName(proxyClass)
                .getMethod("setTarget", Object.class).invoke(proxyFactory, target);
        Class.forName(proxyClass).
                getMethod("setInterceptorManager", Object.class).invoke(proxyFactory, interObj);
        return target;
    }
}
